/**
 * @description: 添加图标文字按钮
 * @param {Array | number} _len 遍历按钮的数量 为数组对象时 对象类型为 {img:string,label:string,src:string}
 * @param {number} is 第几个
 * @param {string} dom 要给追加的dom的类名
 * @param {'append'|'prepend'} fl 追加方式 默认 append尾部追加
 * @param {number} indexStart 此参数为按钮的唯一标识的初始值
 * @param {string} itemClass 初始类名
 * @return {Function}  回调函数
 * @author: 问道师兄木木木
 */
function menu_item(
  _len = 0,
  is = 0,
  dom,
  fl = "append",
  indexStart = 0,
  itemClass
) {
  var len = _len.length || _len;
  var _dom = "";
  var fn = function () {};

  // 是否加载完成所有dom 0 false 1 true -1 异常停止
  var state = 0;

  // 超时保护(防止死循环)  单位毫秒
  var timeOut = 10000;

  var dom_class_list = [];

  function onFunction() {
    setTimeout(function () {
      if (timeOut < 1) return;
      state !== 0 ? fn && fn(dom_class_list) : onFunction();
      timeOut -= 100;
    }, 100);
  }

  function appDom(index, isReset) {
    if (isReset) _dom = "";
    var element = _len[index] || {
      img: "../assets/images/info2-title-box-false.png",
      label: "通讯聊天" + index,
    };
    var _index = index + (indexStart || 0);
    dom_class_list.push("nav-box-item-" + _index);
    _dom += ' <div class="';
    _dom += itemClass || "nav-box-item";
    if (index == is) {
      _dom += " active";
    }
    _dom += " nav-box-item-" + _index + '"';
    _dom += 'data-src="' + element.src + '">';
    _dom += " <img src=" + element.img + " />";
    _dom += " <span>" + element.label + "</span>";
    _dom += " </div>";
  }

  for (let index = 0; index < len; index++) {
    if (state == -1) break;
    setTimeout(function () {
      appDom(index, true);
      $(dom)[fl](_dom);
      if (index == len - 1) state = 1;
    }, index * 40);
  }
  return {
    then(fnc) {
      fn = fnc;
      // 开始监听回调 如果调用then 才执行
      onFunction();
      return {
        stop() {
          state = -1;
        },
      };
    },
    stop() {
      state = -1;
    },
  };
}

/** 4块 点击展开区域 */
function ConCarBox() {
  var _DOM = $(".con-car .con-box");
  var conCarBoxIndex = 0;
  var conCarInter = null;

  _DOM.mouseover(runInterval);
  _DOM.mouseout(destroyInterval);

  _DOM.children(".box-item").mouseenter(function () {
    if (!this.className) return;
    var _index = this.className.toString().replace(/[^\d.]/g, "");
    conCarBoxIndex = _index;
    StartInterval();
    conCarBoxIndex = _index;
  });

  function StartInterval() {
    var len = _DOM.children();
    var i = 0;
    for (i; i < len.length; i++) {
      len[i].className = len[i].className.replace(/active/g, "");
    }
    len[conCarBoxIndex] && (len[conCarBoxIndex].className += " active");
    // var _span = len[conCarBoxIndex].children[1].children[0]

    if (conCarBoxIndex == len.length - 1) conCarBoxIndex = 0;
    else conCarBoxIndex++;
  }

  function runInterval() {
    destroyInterval();
    conCarInter = setInterval(StartInterval, 3000);
  }

  function destroyInterval() {
    clearInterval(conCarInter);
  }
  StartInterval();
  runInterval();
}

function conSwiper() {
  var leftState = false;

  menu_item(
    detectMobile() ? btnMeeting5 : btnMeeting,
    0,
    $(".con-nav"),
    "append",
    0,
    "con-nav-item"
  ).then(function () {
    var DOM = $(".con-nav-item");

    $(".con-swiper .con-swiper-item img").attr(
      "src",
      DOM[0].dataset.src
    );
    //  这里异步处理了，上面DOM不会获取下面新加的按钮  新加的按钮 为上面追加的前十个

    !detectMobile() &&
      menu_item(
        btnMeeting.slice(0, 9),
        -1,
        $(".con-nav"),
        "append",
        DOM.length,
        "con-nav-item"
      ).then(function (res) {
        res.map(function (element) {
          $("." + element).click(function () {
            swiper_active(2, -(getIndex(element) - DOM.length));
          });
        });
      });

    //  这里异步处理了，上面DOM不会获取下面新加的按钮  新加的按钮 为上面追加的最后一个
    !detectMobile() &&
      menu_item(
        [btnMeeting[btnMeeting.length - 1]],
        -1,
        $(".con-nav"),
        "prepend",
        -1,
        "con-nav-item con-nav-item--1"
      ).then(function (res) {
        res.map(function (element) {
          $("." + element).click(function () {
            swiper_active(2, DOM.length - 1);
          });
        });
      });

    /** 当前轮播图的索引 */
    var animation_swiper_index = 0;
    var animation_swiper_time = null;
    /** 手机的点击计时处理 这个是单词  setTimeout 计时器*/
    var animation_swiper_mobile_time = null;

    DOM.click(function () {
      destroyInterval();
      swiper_active(2, this.className.replace(/[^\d.]/g, ""));

      //  点击后的两秒如果没有再次点击，继续执行计时轮播事件
      animation_swiper_mobile_time = setTimeout(() => {
        destroyInterval();
        runInterval();
      }, 5000);
    });

    handleTouch("#con-swiper-item")(
      function () {
        destroyInterval();
        swiper_active(2, getIndex(this.className));

        //点击后的两秒如果没有再次点击，继续执行计时轮播事件
        animation_swiper_mobile_time = setTimeout(() => {
          destroyInterval();
          runInterval();
        }, 2000);
      },
      function () {
        destroyInterval();
        swiper_active(1, getIndex(this.className));

        //点击后的两秒如果没有再次点击，继续执行计时轮播事件
        animation_swiper_mobile_time = setTimeout(() => {
          destroyInterval();
          runInterval();
        }, 2000);
      }
    );

    $(".con-last").click(function (e) {
      if (leftState) return;
      destroyInterval();
      swiper_active(1);
    });

    $(".con-next").click(function () {
      if (leftState) return;
      destroyInterval();
      swiper_active(2);
    });

    runInterval();
    $(".con-swiper").hover(destroyInterval, runInterval);

    function runInterval() {
      destroyInterval();
      animation_swiper_time = setInterval(swiper_active, 3000);
    }

    function destroyInterval() {
      clearInterval(animation_swiper_time);
      clearTimeout(animation_swiper_mobile_time);
    }

    /** 执行切换函数 默认是向后执行  state 执行状态 1 向前  2向后； */
    function swiper_active(state = 2, index) {
      /** 保存之前的索引 做动画判断 */
      var old_index = animation_swiper_index;

      if (index) {
        animation_swiper_index = +index;
      } else {
        if (state == 2 && animation_swiper_index == DOM.length - 1) {
          animation_swiper_index = 0;
        } else if (state == 1 && animation_swiper_index == 0) {
          animation_swiper_index = DOM.length - 1;
        } else {
          animation_swiper_index =
            state == 2 ?
            +animation_swiper_index + 1 :
            +animation_swiper_index - 1;
        }
      }

      DOM.removeClass("active");

      DOM[Math.abs(animation_swiper_index)].className += " active";

      /** 判断当前要执行的动画效果 */
      var animation_name =
        old_index > animation_swiper_index ? "active_n" : "active_l";


      if (old_index == DOM.length - 1 && animation_swiper_index == 0) animation_name = 'active_l'
      if (animation_swiper_index == DOM.length - 1 && old_index == 0) animation_name = 'active_n'



      setTimeout(() => {
        /** 这里要给手机中间那张图片赋值src地址 animation_swiper_index 为当前索引*/
        // $('.con-swiper .con-swiper-item img').attr('src', '../assets/test/test43121.png')
        $(".con-swiper .con-swiper-item img").attr(
          "src",
          DOM[Math.abs(animation_swiper_index)].dataset.src
        );
      }, 365);

      $(".con-swiper-item .content").removeClass('active_n');
      $(".con-swiper-item .content").removeClass('active_l');
      setTimeout(function () {
        $(".con-swiper-item .content").addClass(animation_name);
      }, 100);

      !detectMobile() && conNavLeft();

      /** 轮播左移动画 */
      function conNavLeft() {
        var _dom = document.getElementsByClassName("con-nav");
        if (animation_swiper_index > DOM.length + 1) return;
        if (_dom) {
          var left;
          if (animation_swiper_index == DOM.length - 1 && old_index == 0) {
            leftState = true;
            // 第一页
            left = "translateX(-20px)";
            $(".con-nav-item")[0].className += " active";

            setTimeout(function () {
              $(".con-nav").css({
                transform: "translateX(-" + DOM.length * 8.535 + "vw)",
                transition: "none .3666s",
              });
              $(".con-nav-item")[0].className = "con-nav-item";

              leftState = false;
            }, 365);
          } else if (
            animation_swiper_index == 0 &&
            old_index == DOM.length - 1
          ) {
            leftState = true;
            // 最后一页
            left = "translateX(-" + (DOM.length + 1) * 8.435 + "vw)";
            $(".con-nav-item")[DOM.length + 1].className += " active";

            setTimeout(function () {
              $(".con-nav").css({
                transform: "translateX(-8.535vw)",
                transition: "none .3666s",
              });
              $(".con-nav-item")[DOM.length + 1].className = "con-nav-item";

              leftState = false;
            }, 365);
          } else if (animation_swiper_index < 0) {
            leftState = true;
            // 后面追加的
            $(".con-nav").css({
              transform: "translateX(-" +
                (Math.abs(animation_swiper_index) + 1) * 8.435 +
                "vw)",
              transition: "none .3666s",
            });
            return;
          } else {
            left =
              "translateX(-" + (animation_swiper_index + 1) * 8.535 + "vw)";
          }

          $(".con-nav").css({
            transform: left,
            transition: "transform .3666s",
          });
        }
      }
    }
  });
}


$('.con-IM .con-mobile-box .content img').attr('src', btnWrokNormal[0].src || '')
function conMenu() {
  var conMenu1 = ".con-menu-1 .con-menu-items";
  var conMenu2 = ".con-menu-2 .con-menu-items";

  var conMenuInterval = null;
  var conMenuIndex = null;

  menu_item(btnWrokNormal, 0, conMenu1).then(function () {
    menu_item(btnWrokFeature, -1, conMenu2, "append", 6).then(function () {
      $(".con-menu .nav-box-item").mouseenter(click1());
      $(".con-menu .nav-box-item").mouseenter(click2);
      intervalFn(true);
      runInterval();
      $(".con-IM").mouseover(destroyInterval);
      $(".con-IM").mouseout(runInterval);
    });
  });

  function runInterval() {
    destroyInterval();
    conMenuInterval = setInterval(intervalFn, 2500);
  }

  function destroyInterval() {
    clearInterval(conMenuInterval);
  }

  function intervalFn(immediate) {
    if (conMenuIndex == $(".con-menu .nav-box-item").length) {
      conMenuIndex = 0;
    }
    removeClass();
    $(".con-menu .nav-box-item").eq(conMenuIndex)[0].className += " active";
    !immediate && conMenuIndex !== null && click1()($(".con-menu .nav-box-item").eq(conMenuIndex)[0].dataset.src);
    conMenuIndex++;
  }

  function removeClass() {
    $(".con-menu-1 .nav-box-item").removeClass("active");
    $(".con-menu-2 .nav-box-item").removeClass("active");
  }

  function click1() {
    var startID = false;
    return function (e) {
      clearTimeout(startID);
      $(".con-IM .con-mobile-box .content").removeClass("active");


      startID = setTimeout(() => {
        clearTimeout(_tt)
        $(".con-IM .con-mobile-box .content").addClass("active");

        var _tt = setTimeout(() => {
          $('.con-IM .con-mobile-box .content img').attr('src', e.currentTarget ? e.currentTarget.dataset.src : e)
        }, 365);
      }, 100);
    };
  }

  function click2() {
    removeClass();
    this.className += " active";
    conMenuIndex = this.className.toString().replace(/[^\d.]/g, "");
  }
}

// 滑动处理
function handleTouch(select) {
  //小左边滑动
  var startX,
    moveX,
    movebox = document.querySelector(select);

  var leftFn, rightFn;
  //触摸开始
  function boxTouchStart(e) {
    var touch = e.touches[0]; //获取触摸对象
    startX = touch.pageX; //获取触摸坐标
  }
  //触摸移动
  function boxTouchMove(e) {
    var touch = e.touches[0];
    moveX = touch.pageX - startX; //手指水平方向移动的距离
  }
  //触摸结束
  function boxTouchEnd(e) {
    moveDir = moveX < 0 ? true : false; //滑动方向大于0表示向左滑动，小于0表示向右滑动
    //手指向左滑动
    if (moveDir) leftFn && leftFn();
    //手指向右滑动
    else rightFn && rightFn();
  }

  //滑动对象事件绑定
  movebox.addEventListener("touchstart", boxTouchStart, false);
  movebox.addEventListener("touchmove", boxTouchMove, false);
  movebox.addEventListener("touchend", boxTouchEnd, false);

  return function (fn1, fn2) {
    // 左滑
    leftFn = fn1;
    // 右滑
    rightFn = fn2;
  };
}


/** 手机功能区 */
function mobileMenuHandle(head, mobileImages) {
  var _class = "." + head;
  var _id = "#" + head;
  var _swiper
  var _dom = _class + ' .con-menu-items .nav-box-item';


  $(_dom).click(function () {
    $(_dom).removeClass('active')
    this.className += (' active')
    _swiper.slideToLoop(getIndex(this.className))
  });

  $(_id + ' .swiper-wrapper').html(mobileImages.map((el, index) => `<div class="swiper-slide ${index == 0 ? 'init' : ''}">
    <image src="${el}"></image>
  </div>`))


  _swiper = new Swiper(_id, {
    speed: 700,
    slidesPerView: 'auto',
    centeredSlides: true,
    loop: true,
    on: {
      init: function (e) {
        this.slides.removeClass('init');
      },
      slideChange: function (e) {
        var current = this.activeIndex - mobileImages.length
        if (current == -1) current = mobileImages.length - 1
        if (current == mobileImages.length) current = 0

        $(_dom).removeClass('active')
        $(_dom)[current].className += (' active')
      }
    },
  });



}

// 移动 端

if (detectMobile()) {
  menu_item(
    mobileBtns1,
    0,
    ".con-IM-Mobile1 .con-menu-items"
  ).then(function () {
    mobileMenuHandle("con-IM-Mobile1", mobileImages1);
  });

  menu_item(
    mobileBtns2,
    0,
    ".con-IM-Mobile2 .con-menu-items"
  ).then(function () {
    mobileMenuHandle("con-IM-Mobile2", mobileImages2);
  });

} else {
  // pc 端
  // .con-car1 的dom 操作
  ConCarBox();


  $(".con-car2 .con-mobile-item:first-child .content img").attr('src', btnNormal[0].src || '')
  $(".con-car2 .con-mobile-item:last-child .content img").attr('src', btnFeature[0].src || '')



  var conMobileItemPromise = {};
  // 即时通讯 两个手机那块的点击操作  常规功能和特色功能那个
  function conMobileItemFN(e) {

    $(".con-car2 .con-mobile-item:first-child .content img").attr('src', btnNormal[0].src || '')
    $(".con-car2 .con-mobile-item:last-child .content img").attr('src', btnFeature[0].src || '')
    conMobileItemPromise.stop && conMobileItemPromise.stop();
    if (this.className.indexOf("active") != -1) return;
    $(".con-mobile-item").removeClass("active");
    $(".title-box").html("");
    this.className += " active";
    const obj =
      $(".con-mobile-item")[0].className.indexOf("active") > -1 ?
      btnNormal :
      btnFeature;
    conMobileItemPromise = menu_item(obj, 0, ".active .title-box");
    conMobileItemPromise.then(function (res) {
      addMobileClick();
    });
  }

  //下面就是滑动的懒加载操作了
  var conCar2Num = 0;
  var conNavNum = 0;
  var conMenuNum = 0;
  var conMenu_is = 0;
  // 实际想绑定在 scroll 事件上的 handler
  function realFunc(e) {

    var scrollTop =
      document.body.scrollTop || document.documentElement.scrollTop;
    var conCar2 = $(".con-car2").offset();
    var conNav = $(".con-nav").offset();
    var conMenu1 = $(".con-menu-1 .con-menu-items").offset();

    if (scrollTop >= conCar2.top - 400 && conCar2Num++ == 0) {
      const obj =
        $(".con-mobile-item")[0].className.indexOf("active") > -1 ?
        btnNormal :
        btnFeature;

      $(".con-mobile-item.active .title-box").html('')
      conMobileItemPromise = menu_item(obj, 0, ".con-mobile-item.active .title-box")
      conMobileItemPromise.then(function (el) {
        addMobileClick();
        // 即时通讯 两个手机那块的点击操作  常规功能和特色功能那个
        $(".con-mobile-item").mouseover(debounce(conMobileItemFN, 300, true));
      });
    }

    if (scrollTop >= conNav.top - 200 && conNavNum++ == 0) {}
    if (scrollTop >= conMenu1.top - 900 && conMenuNum++ == 0) {
      conMenu();
    }
  }

  realFunc();

  // 采用了防抖动
  window.addEventListener("scroll", throttle(realFunc, 100));

  $(".con-customer .page .item").click(function () {
    $(".con-customer .page .item").removeClass("active");
    this.className += " active";
    $(".con-customer .customer-box").css({
      transform: `translateX(${50 - (getIndex(this.className) - 1) * 100}vw)`,
    });
  });
}




// 视频会议的DOM操作
conSwiper();

function addMobileClick() {
  var startId;
  $(".con-car2 .nav-box-item").mouseenter(function () {
    clearTimeout(startId);

    setTimeout(() => {
      $(".con-car2 con-mobile-item,.active .content img").attr(
        "src",
        this.dataset.src
      );
    }, 400);

    $(".con-car2 con-mobile-item,.active .content").removeClass("active");
    startId = setTimeout(function () {
      $(".con-car2 con-mobile-item,.active .content").addClass("active");
    }, 100);
  });
  $(".con-car2 .nav-box-item").mouseenter(function () {
    $(".con-car2 .nav-box-item").removeClass("active");
    this.className += " active";
  });
}